package com.xm.data.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.xm.data.entiry.StatType;
import org.springframework.stereotype.Component;

@Component
public class DynamicTableHandler implements TableNameHandler {
    private static final ThreadLocal<TableMeta> CONTEXT = new ThreadLocal<>();

    public static void setTableMeta(StatType type, int granularity) {
        CONTEXT.set(new TableMeta(type, granularity));
    }

    public static void clear() {
        CONTEXT.remove();
    }

    private record TableMeta(StatType type, int granularity) {
    }

    @Override
    public String dynamicTableName(String sql, String originalTable) {
        TableMeta meta = CONTEXT.get();
        return meta != null ?
                String.format("history_%s_%dm",
                        meta.type.name().toLowerCase(),
                        meta.granularity) :
                originalTable;
    }
}
